package com.ml.mall.service.order.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ml.mall.bean.req.CouponListCheckReq;
import com.ml.mall.bean.res.coupon.CouponProductRes;
import com.ml.mall.bean.res.coupon.CouponSupplierRes;
import com.ml.mall.bean.res.couppon.CoupponCheckRes;
import com.ml.mall.bean.res.vo.SupplierOrderVO;
import com.ml.mall.bean.res.vo.VariantVO;
import com.ml.mall.consts.CommonConsts;
import com.ml.mall.entity.company.SysCompany;
import com.ml.mall.entity.coupon.SysCoupon;
import com.ml.mall.entity.coupon.SysCouponRecord;
import com.ml.mall.entity.order.SysOrder;
import com.ml.mall.entity.sys.SysUser;
import com.ml.mall.mapper.coupon.*;
import com.ml.mall.mapper.order.SysOrderMapper;
import com.ml.mall.security.JwtUtil;
import com.ml.mall.service.coupon.SysCouponRecordService;
import com.ml.mall.service.coupon.SysCouponService;
import com.ml.mall.service.order.SysOrderCoupponService;
import com.ml.mall.service.shopping.SysShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
* <p>
    *  服务实现类
    * </p>
*
* @author kyyang
* Created 2021-05-24
*/
@Service
@Slf4j
public class SysOrderCoupponServiceImpl extends ServiceImpl<SysOrderMapper, SysOrder> implements SysOrderCoupponService {

    @Autowired
    private SysShoppingCartService sysShoppingCartService;
    @Autowired
    private SysCouponMapper sysCouponMapper ;
    @Autowired
    private SysCouponService sysCouponService;
    @Autowired
    private SysCouponSupplierRelationMapper sysCouponSupplierRelationMapper;
    @Autowired
    private SysCouponSupplierUnuseProductMapper sysCouponSupplierUnuseProductMapper;
    @Autowired
    private SysCouponProductRelationMapper sysCouponProductRelationMapper;
    @Autowired
    private SysCouponRecordService sysCouponRecordService;
    @Autowired
    private SysCouponRecordMapper sysCouponRecordMapper;
    @Override
    public CoupponCheckRes checkCouponByCouponCode(CouponListCheckReq req) {
        log.info("sssss=======",req);
        SysUser sysUser = JwtUtil.getCurrentUser();
        CoupponCheckRes coupponCheckRes = new CoupponCheckRes();
        List<SysCoupon> dbCouponList = new ArrayList<>();
        for(String coupponCode: req.getCouponCodeList()){
            if(null != coupponCode && !"".equals(coupponCode)){
                //查询全部优惠券
                QueryWrapper<SysCoupon> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("coupon_code",coupponCode);
                SysCoupon sysCoupon = sysCouponMapper.selectOne(queryWrapper);
                if(sysCoupon != null){
                    dbCouponList.add(sysCoupon);
                }else{
                    return coupponCheckRes;
                }
                //检测优惠券使用次数；
                int usageNum = sysCouponRecordMapper.selectUseNumByComIdAndCode(sysUser.getCompanyId(),sysCoupon.getCouponCode());
                //超出限制使用的数量
                if(usageNum > sysCoupon.getUsageLimitNum()){
                    coupponCheckRes.setCanUseTogether(false);
                    log.info("===checkCouponByCouponCode==is=out=limit====");
                    return coupponCheckRes;
                }
            }
        }
        if(sysCouponService.checkMultiCoupon( dbCouponList ) == false){
            coupponCheckRes.setCanUseTogether(false);
            log.info("===========");
            return coupponCheckRes;
        }

        //购物车中的商品
        List<VariantVO> variantVOList =  sysShoppingCartService.queryVariantFromCart();
        //分类型查询每一个优惠券是否满足？？？
        for(SysCoupon sysCoupon : dbCouponList){
            log.info("sysCoupon=-======{}",sysCoupon.getCouponType());
            //购物车商品复合的累计金额
            BigDecimal cartVariantMoney = BigDecimal.ZERO;
            //如果是全局优惠券 检测是否满足额度；
            if(sysCoupon.getCouponType().equals(CommonConsts.COUPPON_TYPE_SYSTERM)){
                for( VariantVO variantVO : variantVOList ){
                    BigDecimal totalFee = BigDecimal.valueOf(variantVO.getQuantity()).multiply(variantVO.getPrice());
                    cartVariantMoney = cartVariantMoney.add(totalFee);
                }
            }
            //如果是购物车优惠券；系统承担 可直接使用；
            if(sysCoupon.getCouponType().equals(CommonConsts.COUPPON_TYPE_POSTAGE) && sysCoupon.getBearer().equals(0) ){
                for( VariantVO variantVO : variantVOList ){
                    BigDecimal totalFee = BigDecimal.valueOf(variantVO.getQuantity()).multiply(variantVO.getPrice());
                    cartVariantMoney = cartVariantMoney.add(totalFee);
                }
            }
            //如果是购物车优惠券；检测订单内是否有对应的商户；对应商户的购买金额是否满足；
            if(sysCoupon.getCouponType().equals(CommonConsts.COUPPON_TYPE_POSTAGE) && sysCoupon.getBearer().equals(1) ){
                List<CouponSupplierRes> supplerRelotation = sysCouponSupplierRelationMapper.selectSupplierByCouponCode(sysCoupon.getCouponCode());
                if(supplerRelotation.size() != 0){
                    for(CouponSupplierRes couponSupplierRes : supplerRelotation){
                        for( VariantVO variantVO : variantVOList ){
                            if(couponSupplierRes.getSupplierId().equals(variantVO.getSupplierId())){
                                BigDecimal totalFee = BigDecimal.valueOf(variantVO.getQuantity()).multiply(variantVO.getPrice());
                                cartVariantMoney = cartVariantMoney.add(totalFee);
                            }
                        }
                    }
                }
            }
            //如果是商户优惠券；管理员承担；检测是否有对应的商户；商户额度
            if(sysCoupon.getCouponType().equals(CommonConsts.COUPPON_TYPE_SUPPLIER)){
                List<CouponSupplierRes> supplerRelotation = sysCouponSupplierRelationMapper.selectSupplierByCouponCode(sysCoupon.getCouponCode());
                if(supplerRelotation.size() != 0){
                    for(CouponSupplierRes couponSupplierRes : supplerRelotation){
                        for( VariantVO variantVO : variantVOList ){
                            if(couponSupplierRes.getSupplierId().equals(variantVO.getSupplierId())){
                                BigDecimal totalFee = BigDecimal.valueOf(variantVO.getQuantity()).multiply(variantVO.getPrice());
                                cartVariantMoney = cartVariantMoney.add(totalFee);
                            }
                        }
                    }
                }
            }
            //如果是商品优惠券：符合的商品是否满足购买价格；
            if(sysCoupon.getCouponType().equals(CommonConsts.COUPPON_TYPE_PRODUCT)){
                //查询不可用的商品
                List<CouponProductRes> listVariant = sysCouponProductRelationMapper.selectProductByCouponCode(sysCoupon.getCouponCode());
                //剔除不可用商品
                if(listVariant.size() != 0){
                    for(CouponProductRes couponProductRes : listVariant){
                        for( VariantVO variantVO : variantVOList ){
                            //只统计对应的商品
                            if(couponProductRes.getVariantId().equals(variantVO.getVariantId())){
                                BigDecimal totalFee = BigDecimal.valueOf(variantVO.getQuantity()).multiply(variantVO.getPrice());
                                cartVariantMoney = cartVariantMoney.add(totalFee);
                            }
                        }
                    }
                }

            }
            log.info("cartVariantMoney======{}",cartVariantMoney);
            if(cartVariantMoney.compareTo(sysCoupon.getLowLimitMoney()) == -1 ||
                    cartVariantMoney.compareTo(sysCoupon.getTopLimitMoney()) == 1){
                log.info("cartVariantMoney==not==enught==22222,{}:{}",cartVariantMoney, sysCoupon.getTopLimitMoney());
                coupponCheckRes.setCanUseTogether(false);
                return coupponCheckRes;
            }
        }
        coupponCheckRes.setCanUseTogether(true);
        return coupponCheckRes;
    }


    /**
     * 计算优惠券抵扣金额
     * @return
     * @author Daizh
     * @date 2021/7/13 17:03
     */
    public BigDecimal countCoupponMoneyAndCreatCoupponRecode(List<SupplierOrderVO> supplierOrders,List<String> cupponCodes,Long oid){
        BigDecimal couponMoney = BigDecimal.ZERO;
        //一次查询出全部优惠券
        QueryWrapper<SysCoupon> queryWrapper = new QueryWrapper<>();
        for(String coupponCode: cupponCodes){
            queryWrapper.or().eq("coupon_code",coupponCode);
        }
        List<SysCoupon>  listCouppon = sysCouponMapper.selectList(queryWrapper);
        List <SysCouponRecord> listCoupponRecode = new ArrayList<>();
        SysUser sysUser = JwtUtil.getCurrentUser();
        for(SysCoupon sysCoupon: listCouppon){
            BigDecimal reduceMoney = BigDecimal.ZERO;
            SysCouponRecord sysCouponRecord = new SysCouponRecord();
            sysCouponRecord.setCompanyId(sysUser.getCompanyId());
            sysCouponRecord.setCouponCode(sysCoupon.getCouponCode());
            sysCouponRecord.setOid(oid);
            //查询全部优惠券
            if(sysCoupon.getCouponClass().equals(CommonConsts.COUPPON_CLASS_FIX) && !sysCoupon.getCouponType().equals(CommonConsts.COUPPON_TYPE_POSTAGE)){ //固定值&& sysCoupon.getCouponType()!= CommonConsts.COUPPON_TYPE_POSTAGE
                couponMoney = couponMoney.add(sysCoupon.getCouponMoney());
                reduceMoney = sysCoupon.getCouponMoney();
            }
            //如果是折扣优惠券；从当前商品中统计 ；可用的商品
            if(sysCoupon.getCouponClass().equals(CommonConsts.COUPPON_CLASS_PERCEN) && sysCoupon.getCouponType() != CommonConsts.COUPPON_TYPE_POSTAGE ){
                //百分比优惠券计算优惠额度
                for (SupplierOrderVO supplierOrder : supplierOrders) {
                    if(sysCoupon.equals(CommonConsts.COUPPON_TYPE_SYSTERM)){
                        //全局优惠券:商家金额 * 折扣
                        reduceMoney = supplierOrder.getTotalFee().multiply(sysCoupon.getCouponRate());
                        couponMoney = couponMoney.add( reduceMoney );
                    }
                    if(sysCoupon.equals(CommonConsts.COUPPON_TYPE_SUPPLIER)){
                        //卖家优惠券: 某个商家除去不可用产品 金额* 折扣
                        //查询关联的商家
                        List<SysCompany> listCompany = sysCouponSupplierRelationMapper.selectCompanyInfoByCoupponCode(sysCoupon.getCouponCode());
                        for(SysCompany item:listCompany){
                            if(item.getInviteCode().equals(supplierOrder.getSupplierCode())){
                              //去除不可用商品
                              List<VariantVO> listCanUseCouppon =   supplierOrder.getVariants();
                              //计算可用商品的抵扣
                              for(int keyi = 0 ; keyi < listCanUseCouppon.size() ;keyi ++){
                                  reduceMoney =  listCanUseCouppon.get(keyi).getSellPrice().multiply(sysCoupon.getCouponRate());
                                  couponMoney = couponMoney.add(reduceMoney);
                              }
                            }
                        }
                    }
                    if(sysCoupon.equals(CommonConsts.COUPPON_TYPE_SUPPLIER)){
                        //商品优惠券: 所有商家商品复合的 金额* 折扣
                        List<CouponProductRes> coupoProductList = sysCouponProductRelationMapper.selectProductByCouponCode(sysCoupon.getCouponCode());
                        for(CouponProductRes couponProductRes : coupoProductList){
                            for(VariantVO variantVO : supplierOrder.getVariants()){
                                if(couponProductRes.getVariantId() == variantVO.getVariantId()){
                                    reduceMoney = variantVO.getSellPrice().multiply(sysCoupon.getCouponRate());
                                    couponMoney = couponMoney.add( reduceMoney );
                                }
                            }

                        }
                    }
                }
            }
            //包邮券：全局
            if(sysCoupon.getCouponType() == CommonConsts.COUPPON_TYPE_POSTAGE){
                //如果是系统承担
                if( sysCoupon.getBearer() == 0 ){
                    for(SupplierOrderVO supplierOrderVO : supplierOrders){
                        reduceMoney = supplierOrderVO.getDeliveryFee();
                        couponMoney = couponMoney.add(reduceMoney);
                    }
                }
                //如果是卖家承担；找出关联的卖家 可能是多个
                if( sysCoupon.getBearer() == 1 ){
                    List<SysCompany> listCompany = sysCouponSupplierRelationMapper.selectCompanyInfoByCoupponCode(sysCoupon.getCouponCode());
                    for(SysCompany sysCompany : listCompany){
                       for(SupplierOrderVO supplierOrderVO : supplierOrders){
                           if(supplierOrderVO.getSupplierCode() == sysCompany.getInviteCode()){
                               reduceMoney = supplierOrderVO.getDeliveryFee();
                               couponMoney = couponMoney.add(reduceMoney);
                               if(supplierOrderVO.getVariants() != null && supplierOrderVO.getVariants().size() > 0){
                                   VariantVO variantVO = supplierOrderVO.getVariants().get(0);
                                   sysCouponRecord.setSupplierId(variantVO.getSupplierId());
                               }
                           }
                       }
                    }
                }
            }
            sysCouponRecord.setReduceMoney(reduceMoney);
            listCoupponRecode.add(sysCouponRecord);
        }
        //批量存储优惠券记录;
        sysCouponRecordService.saveBatch(listCoupponRecode);
        //优惠券使用数量增加
        for(SysCouponRecord sysCouponRecord : listCoupponRecode){
            sysCouponMapper.updateCouponUseAmount(sysCouponRecord.getCouponCode());
        }
        return couponMoney;
    }

}
